package com.czl.module_service.fragment

import android.graphics.Color
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.czl.base.base.BaseFragment
import com.czl.base.config.AppConstants
import com.czl.base.data.bean.tengyun.StorehouseBean
import com.czl.base.util.SpHelper
import com.czl.module_base.widget.ScaleCircleNavigator
import com.czl.module_service.BR
import com.czl.module_service.R
import com.czl.module_service.adapter.MultiplePagerAdapter
import com.czl.module_service.adapter.StoreManageAdapter
import com.czl.module_service.bean.MenuItemModel
import com.czl.module_service.databinding.ActivityStoreManageBinding
import com.czl.module_service.databinding.HeaderStoreManageBinding
import com.czl.module_service.extension.loadCompletedData
import com.czl.module_service.system.Constants
import com.czl.module_service.view.ListSheetDialogFragment
import com.czl.module_service.viewmodel.StoreManageViewModel
import net.lucode.hackware.magicindicator.MagicIndicator
import net.lucode.hackware.magicindicator.ViewPagerHelper

@Route(path = AppConstants.Router.Service.F_SERVICE_STORE_MANAGE)
class StoreManageFragment : BaseFragment<ActivityStoreManageBinding, StoreManageViewModel>() {

    private lateinit var mAdapter: StoreManageAdapter

    override fun initContentView(): Int {
        return R.layout.activity_store_manage
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun initData() {
        super.initData()
        viewModel.tvTitle.set("仓库管理")
        viewModel.ivToolbarIconRes.set(R.mipmap.saoma_icon)
        initAdapter()
        reload()
    }

    private fun initAdapter() {
        mAdapter = StoreManageAdapter().apply {
            val binding = HeaderStoreManageBinding.inflate(layoutInflater)
            binding.setVariable(initVariableId(), viewModel)
            addHeaderView(binding.root)
            initViewPager(binding.viewPager, viewModel.menu1)
            initViewPager(binding.viewPager1, viewModel.menu2)
            initMagicIndicator(binding.viewPager1, binding.magicIndicator)
        }
        binding.ryCommon.run {
            layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
            adapter = mAdapter
        }
    }

    private fun initViewPager(view: ViewPager, data: MutableList<MenuItemModel>) {
        view.run {
            offscreenPageLimit = 4
            adapter = MultiplePagerAdapter(
                this@StoreManageFragment,
                data
            )
        }
    }

    private fun initMagicIndicator(viewPager: ViewPager, indicator: MagicIndicator) {
        val scaleCircleNavigator = ScaleCircleNavigator(requireContext())
        scaleCircleNavigator.setCircleCount(2)
        scaleCircleNavigator.setNormalCircleColor(Color.LTGRAY)
        scaleCircleNavigator.setSelectedCircleColor(Color.DKGRAY)
        scaleCircleNavigator.setCircleClickListener(viewPager::setCurrentItem)
        indicator.navigator = scaleCircleNavigator
        ViewPagerHelper.bind(indicator, viewPager)
    }

    override fun initViewObservable() {
        viewModel.uc.loadCompleteEvent.observe(this) { data ->
            data?.maxNum?.let {
                mAdapter.maxNum = it
            }
            loadCompletedData(
                hasNextPage = false,
                isFirstPage = true,
                loadSuccess = data != null,
                total = data?.classList?.size,
                data = data?.classList,
                mAdapter = mAdapter,
                ryCommon = binding.ryCommon,
                smartCommon = binding.smartCommon
            )
        }
        viewModel.uc.loadingEvent.observe(this) {

        }

        viewModel.uc.switchStorehouse.observe(this) {
            showStorehouseSheet(it)
        }

        viewModel.uc.loadStoreEvent.observe(this) { it0 ->
            val storehouseId = SpHelper.decodeInt(Constants.SpKey.STOREHOUSE_ID)

            it0?.list?.let {
                if (it.isNotEmpty()) {
                    //仓库id是否已缓存至本地，仓库id是否包含在查询的仓库列表中
                    val bean = it.findLast { it1 ->
                        it1.storehouseId != null && storehouseId == it1.storehouseId
                    }
                    if (storehouseId == 0 || bean == null) {
                        showStorehouseSheet(it0)
                    } else {
                        setDataAtIndex(bean)
                        viewModel.getAPPIndexTotal()
                    }
                }
            }
        }
    }

    private fun showStorehouseSheet(it: StorehouseBean?) {
        val list = mutableListOf<String>()
        it?.list?.forEach { it1 ->
            it1.storehouseName?.let { it2 ->
                list.add(it2)
            }
        }
        ListSheetDialogFragment.showBottomSheet(childFragmentManager, list) { it1 ->
            setDataAtIndex(it?.list?.get(it1))
        }
    }

    private fun setDataAtIndex(bean: StorehouseBean.StoreHouseListBean?) {

        viewModel.roomList = bean?.roomList
        bean?.storehouseName?.let { it2 ->
            viewModel.currentStore.set(it2)
        }
        bean?.companyId?.let { it2 ->
            SpHelper.encode(Constants.SpKey.COMPANY_ID, it2)
        }
        bean?.manageCompanyId?.let { it2 ->
            SpHelper.encode(Constants.SpKey.MANAGE_COMPANY_ID, it2)
        }
        bean?.manageCompanyName?.let { it2 ->
            SpHelper.encode(Constants.SpKey.MANAGE_COMPANY_NAME, it2)
        }
        bean?.manageCompanyShortName?.let { it2 ->
            SpHelper.encode(Constants.SpKey.MANAGE_COMPANY_SHORT_NAME, it2)
        }
        bean?.storehouseId?.let { it2 ->
            SpHelper.encode(Constants.SpKey.STOREHOUSE_ID, it2)
            viewModel.getAPPIndexTotal()
        }
        bean?.storehouseName?.let { it2 ->
            SpHelper.encode(Constants.SpKey.STOREHOUSE_NAME, it2)
        }
        bean?.storehouseLocatId?.let { it2 ->
            SpHelper.encode(Constants.SpKey.STOREHOUSE_LOCATION_ID, it2)
        }
        SpHelper.encode(Constants.SpKey.STOREHOUSE_LOCATION_NAME, "默认库位")
    }

    override fun reload() {
//        binding.smartCommon.autoRefresh()
        viewModel.getStorehouseByUserId()
    }
}